package org.example.car.system.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.example.car.system.domain.SysDept;
import org.example.car.system.service.SysDeptService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Lin
 * @createDate 2024-06-25 14:42:02
 */
@RestController
@RequestMapping("/system/dept")
public class SysDeptController {
    private final SysDeptService sysDeptService;

    public SysDeptController(SysDeptService sysDeptService) {
        this.sysDeptService = sysDeptService;
    }

    @RequestMapping("/list")
    public List<Tree<String>> list() {
        List<SysDept> sysDepts = sysDeptService.list(null);
        ArrayList<SysDept> lists = CollUtil.newArrayList();
        lists.addAll(sysDepts);
        TreeNodeConfig config = new TreeNodeConfig();
        config.setIdKey("id");
        config.setDeep(3);
        List<Tree<String>> list;
        list = TreeUtil.build(lists, "0", config, (node, tree) -> {
            tree.setId(node.getDeptId().toString());
            tree.setParentId(node.getParentId().toString());
            // 额外的值
            tree.put("deptName", node.getDeptName());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            tree.put("createTime", sdf.format(node.getCreateTime()));
            tree.put("status", node.getStatus());
            tree.put("leader", node.getLeader());
            tree.put("email", node.getEmail());
            tree.put("phone", node.getPhone());
            tree.put("orderNum", node.getOrderNum());
        });
        return list;
    }

    @RequestMapping("query")
    public List<SysDept> query() {
        return sysDeptService.list(null);
    }

    @RequestMapping("update")
    public void update(@RequestBody SysDept sysDept) {
        sysDeptService.update(sysDept);
    }

    @RequestMapping("save")
    public void save(@RequestBody SysDept sysDept) {
        sysDept.setCreateTime(new Date());
        sysDeptService.save(sysDept);
    }

    @RequestMapping("exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException {
        // 每个 Sheet 写入的数据
        int NUM_PER_SHEET = 10000;
        // 获取数据
        List<SysDept> list = sysDeptService.list(null);
        // 获取 Sheet 的个数
        int sheetNum = list.size() % NUM_PER_SHEET == 0 ? list.size() / NUM_PER_SHEET : list.size() / NUM_PER_SHEET + 1;
        // 设置响应参数,并写入到流
        String fileName = new String("导出excel.xlsx".getBytes(), StandardCharsets.ISO_8859_1);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        ServletOutputStream outputStream = response.getOutputStream();
        // 指定写入的文件
        try (ExcelWriter excelWriter = EasyExcel.write(outputStream, SysDept.class).build()) {
            for (int i = 0; i < sheetNum; i++) {
                // 设置 Sheet 的名字（sheet不能相同）
                String sheetName = "sheet" + i;
                System.out.println(sheetName);
                // 生成 Sheet
                WriteSheet writeSheet = EasyExcel.writerSheet(i, sheetName).build();
                int startNum = i * NUM_PER_SHEET;
                int endNum = i == sheetNum - 1 ? list.size() : (i + 1) * NUM_PER_SHEET;
                excelWriter.write(list.subList(startNum, endNum), writeSheet);
            }
            System.out.println("导出成功");
            // 最好放在 finally中
            excelWriter.finish();
        }
    }
}
